import Axios, { AxiosResponse } from "axios";
// 生成条形码
import { IColor } from "@/enum/shape.enum";
import { IResponse } from "@/interface/IAxios";
import router from "@/router";
import { userStore } from "@/store/modules/user/user";
import { clearToken, getToken } from "@/store/modules/user/utils";
import { Message } from "@arco-design/web-vue";
import OSS from "ali-oss";
import { nanoid } from "nanoid";
import http from "../config/http";
import { BASE_URL } from "../config/request";
import { LibraryType } from "./library/types";

type qrcode = {
  text: string;
  /* 二维码的大小 */
  size: number;
  bgcolor: IColor;
  textColor: IColor;
  margin: number;
};

/* 预览二维码 */
export function previewQrCode(data: qrcode) {
  return http.request({
    url: "/template/template/previewQrCode",
    method: "post",
    data
  });
}

type Barcode = {
  bgcolor: string;
  showText: string;
  text: string;
  textColor: string;
  w: string | number;
  h: string | number;
  margin: string | number;
  rotate: number;
};

/* 预览条形码 */
export function previewBarCode(data: Partial<Barcode>) {
  return http.request({
    url: "/template/template/previewBarCode",
    method: "post",
    data
  });
}

type dithered = {
  str: string;
  color: string;
  width: number;
  height: number;
};

/* 图片防抖 */
export function dithered(data: dithered) {
  return http.request({
    url: "/v2/sys/api/floyd",
    method: "post",
    data
  });
}
const uploadURL = `/v2/sys/api/upload`;
/* 上传文件 */
export async function updateFile(
  file: File,

  url: string = uploadURL,
  type?: string
): Promise<AxiosResponse<IResponse<any>>> {
  const formData = new FormData();
  formData.append("file", file);

  if (type) {
    formData.append("type", type.toString());
  }

  const data = await Axios.post(BASE_URL + url, formData, {
    headers: {
      Authorization: getToken()
    }
  });
  if (data.data.code === 500) {
    Message.warning(data.data.msg);
  } else {
    Message.info(data.data.msg);
  }
  return data;
}

/**
 * @description: 上传到服务器
 * @param {string} url
 * @param {File} file
 */
export const uploadToServer = (url: string, file: File) => {
  const formData = new FormData();
  formData.append("file", file);
  return Axios.post(`${BASE_URL}/v2/sys/api${url}`, formData, {
    headers: {
      Authorization: getToken()
    }
  });
};

// 批量绑定模板接口
export async function fileTemplate(url: string, params?: any) {
  const res: any = await Axios.get(BASE_URL + url, {
    headers: {
      Authorization: `Bearer ${getToken()}`,
      ContentType: "multipart/form-data"
    },
    params,
    responseType: "arraybuffer"
  });
  const blob = new Blob([res.data], {
    type: "application/vnd.ms-excel"
  }); // 2.获取请求返回的response对象中的blob 设置文件类型，这里以excel为例
  const url_3 = window.URL.createObjectURL(blob); // 3.创建一个临时的url指向blob对象

  const fileName = decodeURI(res.headers["content-disposition"].split("=")[1]) || "file.xlsx";
  // 4.创建url之后可以模拟对此文件对象的一系列操作，例如：预览、下载
  const a = document.createElement("a");
  a.href = url_3;
  a.download = fileName;
  a.click();
  // 5.释放这个临时的对象url
  window.URL.revokeObjectURL(url_3);
}

// 通用下载方法
export function downloadSystemFile(fileName: string) {
  window.location.href = `${BASE_URL}/common/xlsx?fileName=${encodeURI(fileName)}&delete=${true}`;
}

/* 获取版本信息 */
export function getVersion() {
  return http.request({
    url: "/common/version",
    method: "get"
  });
}

interface OssResponse {
  bucket: string;
  accessKeyId: string;
  accessKeySecret: string;
  region: string;
  stsToken: string;
}

export const ossRequest = (): Promise<IResponse<OssResponse>> => {
  return http.request({
    url: "v2/sys/api/sts/token",
    method: "get"
  });
};

interface OssUploadParams {
  file: File;
  randomName: boolean;
  type: LibraryType;
}
export const ossUpload = async (config: OssUploadParams) => {
  const { data: ossData } = await ossRequest();
  const store = userStore();
  const path = store.$state.paths[config.type];

  const ossConfig: OSS.Options = {
    accessKeyId: ossData.accessKeyId,
    accessKeySecret: ossData.accessKeySecret,
    region: ossData.region,
    bucket: ossData.bucket,
    stsToken: ossData.stsToken,
    secure: true
  };
  const client = new OSS(ossConfig);

  const options: OSS.PutObjectOptions = {
    mime: "json",
    headers: {
      "Content-Type": "multipart/form-data; boundary=----WebKitFormBoundaryGTuMLzXcmYqWQYmv"
    }
  };
  let fullName = "";
  if (config.randomName) {
    fullName = `${path}${nanoid(32)}.${config.file.name.split(".")[1]}`;
  } else {
    fullName = `${path}${config.file.name}`;
  }

  const data = await client.put(fullName, config.file, options);
  await client.putACL(fullName, "public-read");

  return data;
};
export const logoff = () => {
  localStorage.removeItem("user");

  localStorage.removeItem("lang");
  Message.success("Success");
  clearToken();
  router.push("/login");
};
